namespace Digitalmes.Application.Mes;

/// <summary>
/// 产品用料表服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "mes")]
public sealed class ProdMaterialConsumeService : IDynamicWebApiService
{
    private readonly SugarRepository<ProdMaterialConsume> _thisRepository;

    public ProdMaterialConsumeService(SugarRepository<ProdMaterialConsume> thisRepository)
    {
        _thisRepository = thisRepository;
    }

    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ProdMaterialConsumeDto>> GetPagesAsync(MaterialConsumePageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(param.Sn), s => s.Sn == param.Sn)
            .WhereIF(!string.IsNullOrWhiteSpace(param.Barcode), s => s.Barcode == param.Barcode)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<ProdMaterialConsumeDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ProdMaterialConsumeDto> GetAsync(long id)
    {
        var model = await _thisRepository.GetByIdAsync(id);
        return model.Adapt<ProdMaterialConsumeDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> AddAsync(ProdMaterialConsumeDto model)
    {
        return await _thisRepository.InsertAsync(model.Adapt<ProdMaterialConsume>());
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ModifyAsync(ProdMaterialConsumeDto model)
    {
        return await _thisRepository.UpdateAsync(model.Adapt<ProdMaterialConsume>());
    }

    /// <summary>
    /// 解绑
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpPut]
    public async Task<bool> UnboundAsync(ProdMaterialConsumeDto model)
    {
        var item = await _thisRepository.GetByIdAsync(model.Id);
        if (item == null)
        {
            return true;
        }

        item.IsUnbound = true;
        return await _thisRepository.UpdateAsync(item, s => new { s.IsUnbound, s.UpdateTime, s.UpdateUser });
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody] List<long> ids) =>
        await _thisRepository.DeleteAsync(m => ids.Contains(m.Id));
}
